/*
 *  PythonPDL.cpp
 *  PythonPDL
 *
 *  Created by Ezequiel Aceto on 5/15/11.
 *  Copyright 2011 Xenat. All rights reserved.
 *
 */
#include "PythonPDL.h"

bool decompress = false;
bool decompressFinished = false;

int main(int argc, char** argv) {
    // open if(debug) syslog in case we want to print out some debugging
    //openlog(PACKAGEID, 0, LOG_USER);
	
    // Initialize the SDL library
    int result = SDL_Init(SDL_INIT_VIDEO);
    if ( result != 0 )
    {        
        exit(1);
    }
	
    PDL_Init(0);
	
    // register the JS callbacks
    PDL_RegisterJSHandler("isPluginAlive", isPluginAlive);
    PDL_RegisterJSHandler("isPythonInstalled", isPythonInstalled);
	PDL_RegisterJSHandler("uncompressPython", uncompressPython);
	PDL_RegisterJSHandler("isDecompressFinished", isDecompressFinished);	
	
    PDL_JSRegistrationComplete();

    SDL_Event Event;
	
    do {
		
		while (true) {

			if (decompress == true) {
				decompress = false;
				system("mkdir /media/internal/python");
				system("/bin/tar -xvf /media/internal/python.tar.gz  -C /media/internal/");				
				decompressFinished = true;				
			}
			
			//SDL_WaitEvent(&Event)
			if (SDL_PollEvent(&Event)) {
			 
				switch (Event.type) {
                    // List of keys that have been pressed
					case SDL_KEYDOWN:
						switch (Event.key.keysym.sym) {
							// Escape forces us to quit the app
							case SDLK_ESCAPE:
								Event.type = SDL_QUIT;
								break;
						}
						break;
					
					default:
						break;
				}
			}
		}

    } while (Event.type != SDL_QUIT);
	
	
    PDL_Quit();
    SDL_Quit();
	
    return 0;
}

PDL_bool uncompressPython(PDL_JSParameters *params) {
	decompressFinished = false;
	decompress = true;	
	PDL_JSReply(params, "Uncompressing");	
	return PDL_TRUE;
}

PDL_bool isDecompressFinished(PDL_JSParameters *params) {
	if (decompressFinished == true) {
		PDL_JSReply(params, "true");
	}
	else {
		PDL_JSReply(params, "false");
	}
	return PDL_TRUE;
}

PDL_bool isPluginAlive(PDL_JSParameters *params){
	decompress = false;
	decompressFinished = false;
	PDL_JSReply(params, "true");
	return PDL_TRUE;
}


PDL_bool isPythonInstalled(PDL_JSParameters *params) {
	decompress = false;
	decompressFinished = false;
	system("rm version.info");	
	system("/media/internal/python/bin/python vercheck.py");
	bool exist = false;
	
	ifstream fin("version.info");
	
	string line = "HOLA";
	if (fin != NULL) {
		getline(fin,line);
		exist = true;
	}
	
	if (exist) {
		PDL_JSReply(params,line.c_str());
	}
	else {
		PDL_JSReply(params,line.c_str());
	}
	return PDL_FALSE;
}